package com.xuecheng.ucenter.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.FeignClient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 冯佳鑫 又菜又爱学
 * @version 1.0
 * @DATE now()
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    CheckCodeClient checkCodeClient;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
//        //拿到验证码
//        String checkcode = authParamsDto.getCheckcode();
//        //拿到验证码的key
//        String checkcodekey = authParamsDto.getCheckcodekey();
//        //如果验证码或者key都为空
//        if (StringUtils.isEmpty(checkcode)||StringUtils.isEmpty(checkcodekey)){
//            throw new RuntimeException("请输入验证码");
//        }
//        //远程调用验证码====
//        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
//        if (verify==false||verify==null){
//            throw new RuntimeException("输入的验证码有误");
//        }


        //根据账户查询用户信息

        LambdaQueryWrapper<XcUser> xcUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xcUserLambdaQueryWrapper.eq(XcUser::getUsername,authParamsDto.getUsername());
        XcUser xcUser = xcUserMapper.selectOne(xcUserLambdaQueryWrapper);
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);
        if (xcUser==null){
            throw new RuntimeException("账号不存在");
        }
        //取出数据库存储的正确密码
        String passwordDb = xcUser.getPassword();
        //前端传来的密码（加密过）
        String password1 = authParamsDto.getPassword();
        //校验密码
        boolean matches = passwordEncoder.matches(password1, passwordDb);
        if (!matches){
            throw new RuntimeException("账号或者密码错误");
        }

        return xcUserExt;
    }
}
